<template>
  <div class="live-stream">
    <!-- 标题 -->
    <div class="panel-header">
      <h3 class="panel-title">设备列表</h3>
    </div>
    <!-- 内容 -->
    <div class="panel-content">
      <!-- 名称 -->
      <div class="live-name">
        <el-input v-model="searchInput" placeholder="请输入搜索内容"></el-input>
      </div>
      <!-- 画面容器 -->
      <div class="live-stream-container" v-loading="loading">
        <!-- 画面本身 -->
        <div 
          class="live-stream-item" 
          v-for="device in filteredDevices" 
          :key="device.device_id || device.id"
          @click="handleDeviceClick(device)"
          :class="{ 'selected': selectedDeviceId === (device.device_id || device.id) }"
        >
          <div class="live-stream-item-img">
            <el-image class="image-panel-image" fit="fill" :src="planeImg" />
          </div>
          <div class="live-stream-item-info">
            <div class="live-stream-item-name">{{ device.device_name || device.name || 'DJI Flip 畅飞套装' }}</div>
            <span class="live-stream-item-type">
              {{ device.device_type || '机场相机' }}
            </span>
          </div>
          <div class="live-stream-item-status" :class="{ 'online': isDeviceOnline(device.status), 'offline': !isDeviceOnline(device.status) }">
            <el-image class="image-panel-image" fit="fill" :src="getStatusIcon(device.status)" />
            {{ getStatusText(device.status) }}
          </div>
        </div>
        
        <!-- 无数据显示 -->
        <div v-if="!loading && filteredDevices.length === 0" class="no-data">
          <div class="no-data-text">{{ devices.length === 0 ? '暂无设备' : '无匹配设备' }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElImage, ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/modules/user'
import { getDevices, startLiveStream } from '@/api/device'
import planeImg from '@/assets/images/plane_bg.png'
import planeStuatsOnline from '@/assets/images/device_airline_online.png'
import planeStuatsOffline from '@/assets/images/device_airline_offline.png'

const userStore = useUserStore()

// 响应式数据
const devices = ref([])
const searchInput = ref('')
const loading = ref(false)
const selectedDeviceId = ref(null)

// 过滤后的设备列表
const filteredDevices = computed(() => {
  if (!searchInput.value.trim()) {
    return devices.value
  }
  const keyword = searchInput.value.toLowerCase()
  return devices.value.filter(device => {
    const name = (device.device_name || device.name || '').toLowerCase()
    const type = (device.device_type || '').toLowerCase()
    return name.includes(keyword) || type.includes(keyword)
  })
})

// 判断设备是否在线
const isDeviceOnline = (status) => {
  return status === true || status === 'true'
}

// 获取设备状态图标
const getStatusIcon = (status) => {
  if (status === true || status === 'true') {
    return planeStuatsOnline
  } else {
    return planeStuatsOffline
  }
}

// 获取设备状态文本
const getStatusText = (status) => {
  if (status === true || status === 'true') {
    return '在线'
  } else {
    return '离线'
  }
}

// 转换URL格式为WebRTC格式
const convertToWebRTCUrl = (url) => {
  if (!url) return url
  
  console.log('转换前的URL:', url)
  
  // 如果已经是webrtc://格式，直接返回
  if (url.startsWith('webrtc://')) {
    return url
  }
  
  // 如果是rtmp://格式，转换为webrtc://
  if (url.startsWith('rtmp://')) {
    const converted = url.replace('rtmp://', 'webrtc://')
    console.log('RTMP转换为WebRTC:', converted)
    return converted
  }
  
  // 如果是http://或https://格式，尝试转换为webrtc://
  if (url.startsWith('http://') || url.startsWith('https://')) {
    // 移除协议部分
    let cleanUrl = url.replace(/^https?:\/\//, '')
    
    // 如果包含端口号，保留端口号
    if (cleanUrl.includes(':')) {
      const [host, port, ...path] = cleanUrl.split('/')
      const [hostname, portNum] = host.split(':')
      if (portNum) {
        return `webrtc://${hostname}:${portNum}/${path.join('/')}`
      }
    }
    
    // 默认使用1985端口
    return `webrtc://${cleanUrl}`
  }
  
  // 如果是其他格式，尝试添加webrtc://前缀
  if (!url.includes('://')) {
    return `webrtc://${url}`
  }
  
  console.log('无法识别的URL格式，使用原地址:', url)
  return url
}

// 处理设备点击事件
  const handleDeviceClick = async (device) => {
    const deviceId = device.device_id || device.id
 
    console.log('设备信息:', device)
    
  // 检查设备是否在线
  if (!isDeviceOnline(device.status)) {
    ElMessage.warning(`设备 ${device.device_name || device.name || '未知设备'} 当前离线`)
    return
  }
    
  // 更新选中状态
  selectedDeviceId.value = deviceId
  
  // 发送设备选择事件给StatusPanel
  const customEvent = new CustomEvent('device-selected', {
    detail: { 
      device
      // 如果没有指定屏幕索引，不发送screenIndex，让StatusPanel使用默认屏幕
    }
  })
  window.dispatchEvent(customEvent)
  console.log('发送设备选择事件:', device)
  
  // 获取视频流地址
    let live_params = null
    
    // 获取 children 下的 live_params
    if (device.children && device.children.live_params) {
      live_params = device.children.live_params
      console.log('live_params:', live_params)
    } else if (Array.isArray(device.children)) {
      console.log('children 是数组，查找 live_params:')
      device.children.forEach((child, index) => {
        if (child.live_params) {
          live_params = child.live_params
          console.log(`children[${index}].live_params:`, live_params)
        }
      })
    } else {
      console.log('未找到 children 或 live_params')
    }
    
    // 如果找到了 live_params，调用启动直播流接口
    if (live_params) {
      try {
        console.log('调用启动直播流接口，参数:', live_params)
        const response = await startLiveStream(live_params)
        console.log('接口返回结果:', response)
      console.log('接口返回数据类型:', typeof response)
      console.log('接口返回数据结构:', JSON.stringify(response, null, 2))
        
      // 检查response的所有可能路径
      let streamUrl = null
        if (response && response.url) {
        streamUrl = response.url
        console.log('找到URL在response.url:', streamUrl)
      } else if (response && response.data && response.data.url) {
        streamUrl = response.data.url
        console.log('找到URL在response.data.url:', streamUrl)
      } else if (response && response.data && response.data.data && response.data.data.url) {
        streamUrl = response.data.data.url
        console.log('找到URL在response.data.data.url:', streamUrl)
      } else {
        console.log('接口返回结果中没有找到url字段，使用测试地址')
        // 使用测试地址
        streamUrl = 'webrtc://192.168.1.100:1985/live/test'
        console.log('使用测试流地址:', streamUrl)
      }
      
      // 转换URL格式为WebRTC格式
      streamUrl = convertToWebRTCUrl(streamUrl)
      console.log('转换后的WebRTC地址:', streamUrl)
      
      // 获取停止播放参数
      let stop_live_params = null
      if (device.children && device.children.stop_live_params) {
        stop_live_params = device.children.stop_live_params
        console.log('找到stop_live_params:', stop_live_params)
      } else if (Array.isArray(device.children)) {
        device.children.forEach((child, index) => {
          if (child.stop_live_params) {
            stop_live_params = child.stop_live_params
            console.log(`children[${index}].stop_live_params:`, stop_live_params)
          }
        })
      }

      // 发送事件给StatusPanel
      const streamEvent = new CustomEvent('live-stream-ready', {
            detail: { 
              device,
              streamUrl: streamUrl,
              stopLiveParams: stop_live_params
              // 如果没有指定屏幕索引，不发送screenIndex，让StatusPanel使用默认屏幕
            }
          })
      window.dispatchEvent(streamEvent)
      console.log('发送流地址给StatusPanel:', streamUrl)
      
      // 显示成功消息
      ElMessage.success(`设备 ${device.device_name || device.name || '未知设备'} 视频流已准备就绪`)
      
      } catch (error) {
        console.error('调用接口失败:', error)
      ElMessage.error('获取视频流失败')
      }
    } else {
      console.log('没有找到 live_params，跳过接口调用')
    }
  }

// 当前正在选择设备的屏幕索引
const currentSelectingScreen = ref(null)

// 监听设备选择请求
const handleSelectDeviceRequest = (event) => {
  const { screenIndex } = event.detail
  currentSelectingScreen.value = screenIndex
  console.log('收到设备选择请求，屏幕索引:', screenIndex)
  
  // 可以在这里显示设备列表或高亮显示
  ElMessage.info(`请从左侧设备列表中选择设备添加到屏幕${screenIndex + 1}`)
}

// 获取设备列表
const fetchDevices = async () => {
  try {
    loading.value = true
    
    const workspaceId = userStore.user?.workspaceId
    if (!workspaceId) {
      ElMessage.error('未找到工作空间ID')
      return
    }
    
    const response = await getDevices(workspaceId)
    devices.value = response?.data || response || []

    console.log('%c设备列表', 'color: #ff69b4; font-weight: bold;', devices.value);
    
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error('获取设备列表失败')
    devices.value = []
  } finally {
    loading.value = false
  }
}

// 组件挂载后获取数据
onMounted(() => {
  fetchDevices()
  // 添加事件监听器
  window.addEventListener('select-device-for-screen', handleSelectDeviceRequest)
})

// 组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('select-device-for-screen', handleSelectDeviceRequest)
})
</script>

<style lang="scss" scoped>
.live-stream {
  width: 404px;
  height: 903px;
  background: url('@/assets/images/device_airline_bg.png') no-repeat center center;
  background-size: 100% 100%;
  display: flex;
  flex-flow: column nowrap;
  justify-content: flex-start;
  align-items: flex-start;
  
  .panel-header {
    width: 100%;
    height: 38px;
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    align-items: center;
    padding: 0 16px;
    box-sizing: border-box;
    
    .panel-title {
      font-size: 18px;
      font-weight: 900;
      letter-spacing: 2px;
      line-height: 18px;
      vertical-align: top;
      background: linear-gradient(180deg, rgba(238, 238, 238, 1) 0%, rgba(238, 238, 238, 1) 40%, rgba(59, 135, 202, 1) 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      filter: drop-shadow(0px 2px 3px rgba(0, 0, 0, 0.5));
      position: relative;
      bottom: -2px;
    }
  }
  
  .panel-content {
    flex: 1;
    width: 100%;
    padding: 28px 16px 31px;
    box-sizing: border-box;
    
    .live-name {
      display: flex;
      flex-flow: row nowrap;
      justify-content: flex-start;
      align-items: center;
      margin-bottom: 10px;

      :deep(.el-input) {
        height: 32px !important;
        
        .el-input__wrapper {
          height: 32px !important;
          border-left: none !important;
          border-right: none !important;
          background-color: transparent !important;
        }
        
        .el-input__inner {
          height: 30px !important;
          line-height: 30px !important;
        }
      }
    }
    
    .live-stream-container {
      position: relative;
      width: 373px;
      max-height: 780px;
      overflow-y: auto;
      background: rgba(7, 44, 54, 1);
      border: 1px solid rgba(90, 120, 140, 1);
      margin-bottom: 16px;
      
      .live-stream-item {
        width: 100%;
        height: 100px;
        display: flex;
        flex-flow: row nowrap;
        justify-content: flex-start;
        align-items: center;
        border-bottom: 1px solid rgba(90, 120, 140, 0.3);
        cursor: pointer;
        transition: background-color 0.3s ease;
        
        &:last-child {
          border-bottom: none;
        }
        
        &:hover {
          background-color: rgba(90, 120, 140, 0.1);
        }
        
        &.selected {
          background-color: rgba(59, 135, 202, 0.2);
          border-left: 3px solid rgba(59, 135, 202, 1);
        }

        .live-stream-item-img{
          padding: 0 10px;
          width: 84px;
          height: auto;
          
          img {
            width: 100%;
            height: 100%;
          }
        }

        .live-stream-item-info{
          flex: 1;
          .live-stream-item-name{
            margin-bottom: 10px;
            font-size: 16px;
            font-weight: 600;
            color: #FFFFFF;
          }
          .live-stream-item-type{
            padding: 2px 4px;
            color: #FFFFFF;
            font-size: 12px;
            background: #146D8E;
            border-radius: 4px;
          }
        }
             
        .live-stream-item-status{
          width: 60px;
          font-size: 12px;
          color: #FFFFFF;
          text-align: center;
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: center;
          gap: 4px;
          
          .image-panel-image {
            width: 16px;
            height: 16px;
          }
          
          &.online {
            color: #67C23A;
          }
          
          &.offline {
            color: #F56C6C;
          }
        }
      }
      
      .no-data {
        width: 100%;
        height: 200px;
        display: flex;
        justify-content: center;
        align-items: center;
        
        .no-data-text {
          color: rgba(255, 255, 255, 0.6);
          font-size: 14px;
        }
      }
    }
  }
}

// 滚动条样式
.live-stream-container::-webkit-scrollbar {
  width: 4px;
}

.live-stream-container::-webkit-scrollbar-track {
  background: rgba(90, 120, 140, 0.2);
}

.live-stream-container::-webkit-scrollbar-thumb {
  background: rgba(90, 120, 140, 0.8);
  border-radius: 2px;
}

.live-stream-container::-webkit-scrollbar-thumb:hover {
  background: rgba(90, 120, 140, 1);
}
</style> 